package org.noootsab.gae.games.tzaar.log {
import mx.containers.TitleWindow;
import mx.containers.VBox;
import mx.controls.Label;
import mx.core.Container;
import mx.core.mx_internal;
import mx.events.CloseEvent;
import mx.logging.ILogger;
import mx.logging.LogEvent;
import mx.logging.LogEventLevel;
import mx.logging.targets.LineFormattedTarget;
import mx.managers.PopUpManager;

use namespace mx_internal;

public class LogConsoleWindowTraceTarget extends LineFormattedTarget {
    private var consoleWindow:TitleWindow;

    public function LogConsoleWindowTraceTarget() {
        super();

        // change the defaults for these
        super.fieldSeparator = "##";
        super.includeTime = true;
        super.includeDate = true;
        super.includeCategory = true;
        super.includeLevel = true;
        super.filters = ["org.noootsab.*"];
        super.level = LogEventLevel.ALL;

        consoleWindow = new TitleWindow();
        consoleWindow.title = "Log Window";
        var vBox:VBox = new VBox();
        vBox.name = "logList";
        consoleWindow.addChild(vBox);
        consoleWindow.showCloseButton = true;
        consoleWindow.width = 400;
        consoleWindow.height = 400;
    }

    public override function logEvent(event:LogEvent):void {
        // Take care to NOT include mx.*, as code in std lib issues log calls,
        // which will call this target, which will send a message to server
        // (through rpc operation), which will log to this again, ... until StackOverflowException
        var category:String = ILogger(event.target).category;
        if (category.indexOf("mx.") != 0) {
            super.logEvent(event);
        }
    }

    /**
     *  Super class calls this method when it has formatted the message
     *  and wants to send it somewhere.
     *  The default implementation does nothing.
     */
    mx_internal override function internalLog(message:String):void {
        var label:Label = new Label();
        label.text = message;
        (consoleWindow.getChildByName("logList") as VBox).addChild(label);
    }

    public function show(container:Container):void {
        PopUpManager.addPopUp(consoleWindow, container, false);
        PopUpManager.centerPopUp(consoleWindow);
        var remove:Function = function (event:CloseEvent):void {
            PopUpManager.removePopUp(consoleWindow);
            consoleWindow.removeEventListener(CloseEvent.CLOSE, arguments.callee);
        }
        consoleWindow.addEventListener(CloseEvent.CLOSE, remove);
    }
}
}